package com.imooc.bilibili.handler;

import com.imooc.bilibili.exception.ConditionException;
import com.imooc.bilibili.result.Result;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE) //确定最高执行优先级
public class CommonGlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result<String> commonExceptionHandler(HttpServletRequest request,Exception exceptione) {
        String errorMessage = exceptione.getMessage();
        if (exceptione instanceof ConditionException) {
            String errorCode = ((ConditionException) exceptione).getCode();
            return new Result<>(errorCode,errorMessage);
        } else {
            return new Result<>("500",errorMessage);
        }
    }
}
